
package com.kugou.game.sdk.ui.activity;

import com.kugou.framework.base.LogUtil;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.IEventCode;
import com.kugou.game.sdk.api.common.IEventDataField;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.PlatformEventDispatcher;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.interfaces.OnModifyPasswordListener;
import com.kugou.game.sdk.ui.widget.LoadingView;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 描述:注册成功、修改密码界面
 * 
 * @author jiec
 * @since 2014-11-25 上午11:18:54
 */
public class RegisterSuccessActivity extends BaseCommonTitleFragmentActivity {
    /**
     * 消息相关
     */
    private static final int MSG_REQUEST_CHANGE = 1;// 提交注册请求

    private static final int MSG_CHANGE_SUCCESS = 2;// 注册成功

    private static final int MSG_CHANGE_FAILE = 3;// 注册失败

    private static final int MSG_START_LOADING = 4;

    /**
     * 控件相关
     */

    private TextView mUserNameTextView, mPasswdTextView, mRegisterTips;

    private EditText mNewPasswordEditText;

    private LoadingView mLoadingView;

    private ScrollView mLayoutScrollView;

    private Button mChangePasswdBtn, mEnterGameBtn;

    private int mFrom;

    /**
     * 固定充值金额（来自于固定充值界面，用于判断注册成功后回跳转至固定充值界面）
     */
    private int fixedNum;

    private String mUserName, mPasswd;

    private User mUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int layoutId = Rx.layout.kg_register_one_key_success_activity;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_register_one_key_success_activity_land;
        }

        if (layoutId != 0) {
            setContentView(layoutId);
            // 设置标题
            setCommonTitle(Rx.string.kg_register_title);
            // 获取从其他页面跳转过来传递过来的参数
            mFrom = getIntent().getIntExtra(FROM_ACTION_KEY, FROM_NORMAL);
            fixedNum = getIntent().getIntExtra(RechargeActivity.FIXED_MONEY_NUM, -1);
            mUserName = getIntent().getStringExtra(PHONE);
            mPasswd = getIntent().getStringExtra(PASSWORD);
            mUser = (User) getIntent().getSerializableExtra(USER);

            // 初始化控件
            initViews();
            // 设置View界面
            // initValidateUi();
        } else {
            showToast(Rx.string.kg_layout_not_found);
        }
    }

    /**
     * 初始化页面
     */
    private void initViews() {
        mLayoutScrollView = (ScrollView) findViewById(Rx.id.kg_layout_scrollview);
        mLoadingView = (LoadingView) findViewById(Rx.id.kg_loading);
        mLoadingView.setText("正在修改密码，请稍候...");

        mRegisterTips = (TextView) findViewById(Rx.id.kg_register_tips);

        mUserNameTextView = (TextView) findViewById(Rx.id.kg_tv_register_kugou_account);
        mUserNameTextView.setText(mUserNameTextView.getText() + mUserName);

        mPasswdTextView = (TextView) findViewById(Rx.id.kg_tv_register_kugou_passwd);
        mPasswdTextView.setText(Html.fromHtml("<font color=#666666>密码：" + mPasswd + "</font>"));

        mNewPasswordEditText = (EditText) findViewById(Rx.id.kg_et_register_input_passwd);

        mChangePasswdBtn = (Button) findViewById(Rx.id.kg_btn_change_passwd);
        mChangePasswdBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String newPasswd = mNewPasswordEditText.getText().toString().trim();
                if (TextUtils.isEmpty(newPasswd) || newPasswd.length() < 6) {
                    showToast("密码必须为6-20位字母/数字");
                    return;
                }

                if (newPasswd.equals(mPasswd)) {
                    showToast("请输入新密码");
                    return;
                }

                hideSoftInput(RegisterSuccessActivity.this);
                sendEmptyBackgroundMessage(MSG_REQUEST_CHANGE);
            }
        });

        mEnterGameBtn = (Button) findViewById(Rx.id.kg_btn_enter_game);
        mEnterGameBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                enterGame();
            }
        });

        // 如果从巨炮游戏中心跳入，隐藏一些入口
        if (mFrom == FROM_GAME_CENTER) {
            mEnterGameBtn.setVisibility(View.INVISIBLE);
        }

    }

    private void enterGame() {
        Bundle bundle = new Bundle();
        if (mFrom == FROM_RECHARGE) {// 如果来自充值页面，则返回充值
            Intent intent = new Intent(RegisterSuccessActivity.this, RechargeActivity.class);
            intent.putExtra(USER_NICKNAME_KEY, mUser.getAccountName());
            intent.putExtra(RechargeActivity.FIXED_MONEY_NUM, fixedNum);
            startActivity(intent);
            finish();
        } else if (mFrom == FROM_CHANGE_ACCOUNT) {// 如果来自切换账号,根据配置决定是否重启
            bundle.putSerializable(IEventDataField.EXTRA_USER, mUser);
            PlatformEventDispatcher.sendEvent(IEventCode.ACCOUNT_CHANGED_SUCCESS, bundle);
            AppUtil.handleActionsAfterLoginSuccess(IEventCode.ACCOUNT_CHANGED_SUCCESS);
            LogUtil.d("callback", "RegisterActivity:ACCOUNT_CHANGED_SUCCESS");
            // 判断是否需要重启
            boolean isReboot = SDKControler.isNeedRestartWhenAccountChanged();
            if (isReboot) {// 重启游戏
                PlatformEventDispatcher.sendEvent(IEventCode.INTENT_TO_REBOOT_APP, bundle);
                LogUtil.d("callback", "RegisterActivity:INTENT_TO_REBOOT_APP");
                reStart();
            } else {// 返回游戏
                sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            }
        } else if (mFrom == FROM_BEFORE_ENTER_GAME_LOGIN
                || mFrom == FROM_BEFORE_ENTER_GAME_REGISTER) {// 登录或进入游戏之前进入注册，注册成功后通知进入游戏
            bundle.putSerializable(IEventDataField.EXTRA_USER, mUser);
            PlatformEventDispatcher.sendEvent(IEventCode.ENTER_GAME_SUCCESS, bundle);
            AppUtil.handleActionsAfterLoginSuccess(IEventCode.ENTER_GAME_SUCCESS);
            LogUtil.d("callback", "RegisterActivity:ENTER_GAME_SUCCESS");
            // 关闭SDK页面
            sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            finish();
        } else if (mFrom == FROM_GIFTBAG_REGISTER) {// 从礼包页面进入
            bundle.putSerializable(IEventDataField.EXTRA_USER, mUser);
            PlatformEventDispatcher.sendEvent(IEventCode.REGISTER_SUCCESS, bundle);
            AppUtil.handleActionsAfterLoginSuccess(IEventCode.REGISTER_SUCCESS);
            LogUtil.d("callback", "RegisterActivity:REGISTER_SUCCESS");
            sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            // 回到礼包页面
            Intent intent = new Intent(RegisterSuccessActivity.this, GiftBagActivity.class);
            startActivity(intent);

        } else if (mFrom == FROM_GAME_CENTER) {// 来自巨炮游戏中心
            sendBroadcast(new Intent(SDKActions.ACTION_REGISTER_SUCCESS));
            finish();
        } else {// 进入游戏之后的正常注册，包括激活账号
            bundle.putSerializable(IEventDataField.EXTRA_USER, mUser);
            PlatformEventDispatcher.sendEvent(IEventCode.REGISTER_SUCCESS, bundle);
            LogUtil.d("callback", "RegisterActivity:REGISTER_SUCCESS");
            sendBroadcast(new Intent(SDKActions.ACTION_BACK_TO_GAME));
            finish();
        }
    }

    private void resetPasswd() {
        final Message message = new Message();

        String userName = UserManager.getInstance().getCurrentUserInternal().getAccountName();
        String oldPwd = mPasswd;
        final String newPwd = mNewPasswordEditText.getText().toString().trim();
        // 发出修改密码请求
        UserManager.getInstance().modifyPassword(userName, oldPwd, newPwd,
                new OnModifyPasswordListener() {
                    @Override
                    public void onSuccess() {
                        message.what = MSG_CHANGE_SUCCESS;
                        mPasswd = newPwd;
                    }

                    @Override
                    public void onFailed(String errorMsg) {
                        message.what = MSG_CHANGE_FAILE;
                        message.obj = errorMsg;
                    }
                });
        sendUiMessage(message);
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_REQUEST_CHANGE:
                sendEmptyUiMessage(MSG_START_LOADING);
                resetPasswd();
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        switch (msg.what) {
            case MSG_START_LOADING:
                mLayoutScrollView.setVisibility(View.GONE);
                mLoadingView.setVisibility(View.VISIBLE);
                break;
            case MSG_CHANGE_FAILE:
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                showToast((String) msg.obj);
                break;
            case MSG_CHANGE_SUCCESS:
                mLayoutScrollView.setVisibility(View.VISIBLE);
                mLoadingView.setVisibility(View.GONE);
                showToast("密码修改成功！");
                mRegisterTips.setText("密码修改成功！");
                mPasswdTextView.setText(Html.fromHtml("<font color=#666666>密码：</font>"
                        + "<font color=#FE8E35>" + mPasswd + "</font>"));
                break;
        }
    }

    /**
     * 关闭并重启应用
     */
    private void reStart() {
        AppUtil.gc();
        finish();
        clearAllActivityAndRestart();
        // 关闭当前游戏进程，退出应用
        Process.killProcess(Process.myPid());
    }

    /**
     * 清除所有页面并重启应用
     */
    private void clearAllActivityAndRestart() {
        Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(
                getBaseContext().getPackageName());
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    }

    @Override
    protected void onBackBtnClick() {
        enterGame();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                enterGame();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
